const express = require('express');
const axios = require('axios');
const cheerio = require('cheerio');
const cors = require('cors');

const app = express();
app.use(cors());

app.get('/api/scrape-resume', async (req, res) => {
    try {
        const targetUrl = req.query.url;
        if (!targetUrl) {
            return res.status(400).json({ success: false, message: 'URL参数缺失' });
        }

        const response = await axios.get(targetUrl, {
            headers: { 'User-Agent': 'Mozilla/5.0' }
        });

        const $ = cheerio.load(response.data);
        
        // 提取目标简历数据
        const resumeData = {
            basicInfo: {
                name: $('header h1').text().trim(),
                jobTitle: $('header p').text().replace('求职意向：', '').trim(),
                profileImg: $('header .profile-img').attr('src') || 'profile.jpg'
            },
            contacts: {
                phone: $('.contact-info p:nth-child(1)').text().replace('电话:', '').trim(),
                email: $('.contact-info p:nth-child(2)').text().replace('邮箱:', '').trim(),
                github: $('.contact-info p:nth-child(3) a').attr('href') || ''
            },
            education: {
                school: $('.section:nth-of-type(1) .content p:first-child strong').text().trim(),
                major: $('.section:nth-of-type(1) .content p:first-child').text().split('-')[1].trim(),
                period: $('.section:nth-of-type(1) .content p:nth-child(2)').text().trim(),
                courses: $('.section:nth-of-type(1) .content p:nth-child(3)').text().replace('主修课程:', '').trim()
            },
            skills: $('.section:nth-of-type(2) .content li').map((i, el) => $(el).text().trim()).get(),
            projects: [],
            awards: $('.section:nth-of-type(4) .content li').map((i, el) => $(el).text().trim()).get(),
            selfAssessment: $('.section:nth-of-type(5) .content p').text().trim()
        };

        // 提取项目经验
        $('.section:nth-of-type(3) .content').each((i, el) => {
            const project = $(el);
            resumeData.projects.push({
                name: project.find('h3').text().trim(),
                period: project.find('p:nth-child(2)').text().replace('项目时间:', '').trim(),
                description: project.find('p:nth-child(3)').text().replace('项目描述:', '').trim(),
                responsibilities: project.find('p:nth-child(4)').text().replace('个人职责:', '').trim(),
                technologies: project.find('p:nth-child(5)').text().replace('技术栈:', '').trim()
            });
        });

        res.json({ success: true, data: resumeData });

    } catch (error) {
        console.error('爬取错误:', error);
        res.status(500).json({ success: false, message: error.message });
    }
});

app.use(express.static('public'));
app.listen(3000, () => console.log('服务器运行在 http://localhost:3000'));

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});